﻿using System;
using System.Web.UI.WebControls;
using Medianamik.Core;
using Medianamik.Core.Sugar;
using Medianamik.UI.Controls;

namespace Medianamik.UI.ContentManagement
{
    public partial class TemplateManagement : BaseModuleEditionPage<NodeWrapper>
    {
        protected void Page_Init(object sender, EventArgs e)
        {
            if (IsEdition)
                _webSiteId = CurrentNode.DefaultInstance.Properties[MedianamikProperties.MedianamikTemplateWebSiteId]
                    .GetValue<Guid?>();
            else if (!WebSiteId.HasValue)
                Response.Redirect(ReturnURL);
        }

        public override MedianamikFormTemplate MedianamikFormTemplate
        {
            get { return Fields; }
        }

        public override LinkButton SaveButton
        {
            get { return btnSave; }
        }

        protected override string ReturnURL
        {
            get
            {
                return "templatelist.aspx";
            }
        }

        public override Guid? TypeId
        {
            get
            {
                return MedianamikTypes.MedianamikTemplate;
            }
        }

        protected override Guid? ParentNodeId
        {
            get
            {
                return MedianamikModules.ContentManagement;
            }
        }

        private Guid? _webSiteId;
        public virtual Guid? WebSiteId
        {
            get
            {
                if (_webSiteId == null)
                {
                    StringHelper.IsGuid(Request.QueryString[QueryStringParamNames.WebSiteId],
                        ref _webSiteId);
                }

                return _webSiteId;
            }
        }

        protected override void Save(object sender, EventArgs e)
        {
            Page.Validate(BaseMedianamikControl.DefaultValidationGroupName);

            if (IsValid)
            {
                if (IsEdition)
                {
                    base.Save(sender, e);
                }
                else
                {
                    if (WebSiteId.HasValue)
                    {
                        var node = MedianamikFormTemplate.GetFormValue(CurrentNode);
                        node.DefaultInstance.Properties[MedianamikProperties.MedianamikTemplateWebSiteId]
                            .SetValue(WebSiteId.Value);
                        NodeManager.SaveNode(node);
                        Response.Redirect(ReturnURL);
                    }
                }
            }
        }
    }
}